<template>
  <view class="bg-gray-50 w-[750rpx] pb-[150rpx] box-border">
    <!-- 顶部导航 -->
    <PageHeader title="课程详情" :showBack="true"/>


    <!-- 课程封面 -->
    <view
        class="h-[400rpx] bg-gradient-to-b mt-[-30rpx] from-black/30 to-black/50 flex flex-col justify-end p-[40rpx] text-white relative"
    >
      <image
          :src="getFullPath(courseDetailData?.cover ?? '')"
          class="absolute inset-0 w-full h-full object-cover"
          @error="onCoverImageError"
      />
      <view
          class="absolute inset-0 bg-gradient-to-b from-black/30 to-black/50"
      ></view>

      <!-- <view
          class="absolute top-[48rpx] right-[30rpx] bg-orange-500 px-[20rpx] py-[10rpx] rounded-[50rpx] text-[26rpx] font-bold"
      >
        进行中
      </view> -->

      <view class="relative z-2">
        <text class="text-[48rpx] font-bold mb-[20rpx] block"
        >{{ courseDetailData.title }}
        </text
        >
        <view class="flex items-center text-[26rpx] opacity-90">
          <view class="flex items-center mr-[30rpx]">
            <text>{{ courseDetailData.member_number }}人学习</text>
          </view>
          <!-- <view class="flex items-center">
            <image :src="getFullPath(courseDetailData?.teachers_pic ?? '')" class="w-[40rpx] h-[40rpx] rounded-full mr-[12rpx] object-cover bg-[#e6eaf2]" @error="onAvatarError" />
            <text>{{ courseDetailData.teacher_name }}老师</text>
          </view> -->
        </view>
      </view>
    </view>

    <!-- 课表部分 -->
    <view class="bg-white rounded-[25rpx] p-[40rpx] m-[30rpx] shadow-lg">
      <view
          class="text-[36rpx] font-bold text-gray-800 mb-[30rpx] flex items-center"
      >
        <text class="mr-[15rpx]">📅</text>
        <text>课程安排</text>
      </view>

      <view class="flex mb-[30rpx] border-b-2 border-gray-100">
        <view
            v-for="(tab, index) in tabs"
            :key="index"
            class="px-[30rpx] py-[20rpx] text-[28rpx] cursor-pointer relative"
            :class="
            activeTab === index ? 'text-blue-500 font-bold' : 'text-gray-500'
          "
            @click="handleTabChange(index)"
        >
          <text>{{ tab }}</text>
          <view
              v-if="activeTab === index"
              class="absolute bottom-[-2rpx] left-0 right-0 h-[4rpx] bg-blue-500 rounded-[2rpx]"
          ></view>
        </view>
      </view>

      <view class="max-h-[600rpx] overflow-y-auto">
        <view
            v-for="(lesson, index) in filteredList"
            :key="index"
            class="bg-white rounded-[20rpx] shadow-md mb-[20rpx] flex items-center p-[24rpx] cursor-pointer transition-all"
            @click="handleLessonClick(lesson)"
        >
          <view class="w-[72rpx] h-[72rpx] rounded-[16rpx] bg-blue-50 flex items-center justify-center text-[28rpx] text-blue-500 mr-[20rpx] flex-shrink-0">
            <image 
            :src="getFullPath(courseDetailData?.teachers_pic ?? '')" 
            class="w-full h-full rounded-[16rpx] object-cover" 
            @error="onCoverImageError" 
            />
          </view>
          
          <view class="flex-1 min-w-0">
            <text class="text-[28rpx] font-bold text-gray-800 mb-[8rpx] block line-clamp-2">{{ lesson.title }}</text>
            <view class="flex text-[24rpx] text-gray-600 mb-[4rpx]">
              <view class="flex items-center mr-[16rpx]">
                <IconFont name="clock" class="mr-[6rpx]"/>
                <text class="truncate">{{ formatDuration(lesson.duration) }}</text>
                <!-- <text class="truncate">{{ lesson.time }}</text> -->
              </view>
              <!-- <view class="flex items-center">
                <IconFont name="video" class="mr-[6rpx]"/>
                <text class="truncate">{{ formatDuration(lesson.duration) }}</text>
              </view> -->
            </view>
          </view>
          <view
              class="px-[16rpx] py-[8rpx] rounded-[16rpx] text-[24rpx] ml-[12rpx] min-w-[80rpx] max-w-[160rpx] truncate text-center"
              :class="getStatusClass(lesson.status)"
          >
            {{ changeStatusClass(lesson.status) }}
          </view>
        </view>
      </view>
    </view>

    <!-- 签到弹窗 -->
    <view
        v-if="showSignModal"
        class="fixed inset-0 bg-black bg-opacity-70 z-1000 flex items-center justify-center"
        @click="closeSignModal"
    >
      <view
          class="bg-white w-[90%] max-w-[650rpx] rounded-[30rpx] overflow-hidden"
          @click.stop
      >
        <view
            class="bg-gradient-to-r from-purple-600 to-blue-500 text-white p-[30rpx] text-center"
        >
          <text class="text-[36rpx] font-bold mb-[10rpx] block">课程签到</text>
          <text class="text-[28rpx] opacity-90">第5课：交互原型设计实战</text>
        </view>
        <view class="p-[40rpx]">
          <view
              class="flex justify-between mb-[30rpx] p-[20rpx] bg-gray-50 rounded-[20rpx]"
          >
            <view class="text-center">
              <text class="text-[26rpx] text-gray-500 mb-[10rpx] block"
              >签到时间
              </text
              >
              <text class="text-[32rpx] font-bold text-gray-800"
              >14:00-14:10
              </text
              >
            </view>
            <view class="text-center">
              <text class="text-[26rpx] text-gray-500 mb-[10rpx] block"
              >当前时间
              </text
              >
              <text class="text-[32rpx] font-bold text-gray-800">{{
                  currentTime
                }}
              </text>
            </view>
          </view>

          <view
              class="bg-gray-50 rounded-[20rpx] p-[30rpx] mb-[30rpx] text-center"
          >
            <IconFont
                name="map-marker-alt"
                class="text-[60rpx] text-blue-500 mb-[20rpx]"
            />
            <text class="text-[30rpx] text-gray-600 block"
            >南宁市青秀区金湖广场
            </text
            >
            <text class="text-[26rpx] text-gray-500 mt-[15rpx] block">
              距离签到点：
              <text class="text-green-500">125米</text>
            </text>
          </view>

          <nut-button
              type="primary"
              size="large"
              class="w-full text-[32rpx] font-bold bg-green-500"
              @click="handleSignIn"
          >
            <IconFont name="check-circle" class="mr-[15rpx]"/>
            立即签到
          </nut-button>
        </view>
        <view
            class="absolute top-[20rpx] right-[20rpx] text-white text-[40rpx] cursor-pointer"
            @click="closeSignModal"
        >
          <IconFont name="times"/>
        </view>
      </view>
    </view>

  </view>
</template>

<script setup lang="ts">
import {ref, onMounted, onUnmounted, computed, UnwrapRef} from "vue";
import Taro from "@tarojs/taro";
import {IconFont} from "@nutui/icons-vue-taro";
import {getCurrentInstance} from "@tarojs/runtime";
import {getFullPath, post} from "@/utils/request";
import {cacheDataSet} from "@tarojs/shared";
import ren from "@/assets/pic/ren.png";
import renBook from "@/assets/pic/book.png"
import {formatDuration} from "@/utils/comm";
// 响应式数据
const activeTab = ref(3);
const showSignModal = ref(false);
const currentTime = ref("");
const buyStatus = ref(false);

// 标签页
const tabs = ref(["未开始","已结束","进行中","全部课程"]);

// 筛选后的数据（根据活跃标签）
const filteredList = computed(() => {
  // 获取当前标签名称（如 tabs[0] 是“未开始”）
  const currentTab = tabs.value[activeTab.value];

  // 筛选逻辑
  if (currentTab === '全部课程') {
    return lessons.value; // 全部数据
  } else {
    //console.log("lessons.value",lessons.value)
    // 只返回分类匹配当前标签的数据
    return lessons.value.filter(item => item.status === activeTab.value);
  }
});
//定义课程类型
interface Lesson {
  title: string; // 建议用具体类型，而非 null
  time?: string; // 可选字段用 ?
  duration?: number;
  status: number; // 状态为数字（如 1: 未开始, 2: 进行中, 3: 已结束）
  icon?: string;
}
// 课程列表
const lessons = ref<Lesson[]>([]);

// 定时器
let timeInterval: NodeJS.Timeout | null = null;

//获取课程数据
const courseDetailData = ref(
    {
      member_id: null,
      teachers_pic: null,
      sign_rate: null,
      teacher_name: null,
      member_number: null,
      teachers_introduction: null,
      create_time: null,
      pay_number: null,
      title: null,
      type: null,
      cycle_type: null,
      cycle: null,
      cover: null,
      update_time: null,
      pay_status: null,
      total_amount: null,
      price: null,
      progress: null,
      payId: null,
      id: null,
      introduction: null,
      status: null,
      byStatus: null,
    }
)

// 获取状态样式
const getStatusClass = (status: UnwrapRef<null>) => {
  switch (status) {
    case 1:
      return "bg-green-500 text-white";
    case 2:
      return "bg-yellow-400 text-yellow-800 font-bold";
    case 0:
      return "bg-gray-200 text-gray-600";
    default:
      return "bg-gray-200 text-gray-600";
  }
};

//状态文本转换
const changeStatusClass = (status: UnwrapRef<Lesson["status"]>) => {
  switch (status) {
    case 1:
      return "已完成";
    case 2:
      return "进行中";
    case 0:
      return "未开始";
    default:
      return "未开始";
  }
};

// 更新当前时间
const updateTime = () => {
  const now = new Date();
  const hours = now.getHours().toString().padStart(2, "0");
  const minutes = now.getMinutes().toString().padStart(2, "0");
  currentTime.value = `${hours}:${minutes}`;
};

// 标签切换
const handleTabChange = (index: number) => {
  activeTab.value = index;
  console.log("activeTab.value",activeTab.value)
};

// 课程点击
const handleLessonClick = (lesson: any) => {
  console.log("lesson",lesson)
  // 检查是否有视频URL
  if (!lesson.video_url) {
    Taro.showToast({
      title: '该章节暂无视频内容',
      icon: "none",
    });
    return;
  }

  // 将章节列表数据存储到缓存中
  Taro.setStorageSync('chapterList', lessons.value)
  Taro.setStorageSync('courseDetailData', courseDetailData.value)

  // 准备跳转参数（简化参数，不包含章节列表）
  const params = {
    videoUrl: lesson.video_url,
    coverUrl: lesson.chapter_cover || courseDetailData.value?.cover || '',
    title: lesson.title,
    duration: lesson.duration || 0,
    teacherName: courseDetailData.value?.teacher_name || '',
    description: courseDetailData.value?.introduction || '',
    chapterId: lesson.id
  };

  // 跳转到视频播放页面
  Taro.navigateTo({
    url: `/pages/course/video-player?${Object.entries(params)
      .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
      .join('&')}`
  });
};

// 返回
const handleBack = () => {
  Taro.navigateBack();
};

// 分享
const handleShare = () => {
  Taro.showToast({
    title: "分享功能",
    icon: "none",
  });
};

// 申请退款
const handleRefund = () => {
  Taro.showToast({
    title: "已申请退款",
    icon: "success",
  });
};

//支付订单
const handlePayment = () => {
  //获取记录订单id
  const payId = getCurrentInstance().router?.params.payId as string || ""
  const submit = {
    bid: payId
  }
  post('/pay/training', submit).then(res => {
    if (res.code == 0) {
      (window as any).WeixinJSBridge.invoke('getBrandWCPayRequest', {
            "appId": res.data.appid,     //公众号ID，由商户传入
            "timeStamp": res.data.timeStamp,     //时间戳，自1970年以来的秒数
            "nonceStr": res.data.nonceStr,      //随机串
            "package": res.data.prepayId,
            "signType": "RSA",     //微信签名方式：
            "paySign": res.data.paySign //微信签名
          },
          function (res) {
            if (res.err_msg == "get_brand_wcpay_request:ok") {
              // 使用以上方式判断前端返回,微信团队郑重提示：
              //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠，商户需进一步调用后端查单确认支付结果。
              Taro.showToast({title: "购买成功", icon: 'success', duration: 2000})
            } else {
              Taro.showToast({title: "购买失败", icon: 'success', duration: 2000})
            }
          }
      );
    }
  })
  buyStatus.value = true
};

// 打开签到弹窗
const openSignModal = () => {
  showSignModal.value = true;
};

// 关闭签到弹窗
const closeSignModal = () => {
  showSignModal.value = false;
};

// 签到
const handleSignIn = () => {
  Taro.showToast({
    title: "签到成功！您已成功签到第5课",
    icon: "success",
  });

  // 更新课程状态
  const currentLesson = lessons.value.find(
      (lesson) => lesson.status === "进行中"
  );
  if (currentLesson) {
    currentLesson.status = "已完成";
  }

  closeSignModal();
};

function getCourseInformation() {
  const courseId = getCurrentInstance()
  const id = courseId.router?.params.id as string || ""
  const submitData = {
    trainingId: id
  }
  post('/training/getById', submitData).then(res => {
    courseDetailData.value = res.data.columns
    //当pay_status为1时表示商品已经支付了
    if (courseDetailData.value.pay_status == 1) {
      buyStatus.value = true
    }
    if (res.code === 0) {
      const submitId = {
        trainingId: courseDetailData.value.id
      }
      post('/training/list', submitId).then(res => {
        lessons.value = res.data.map((item: any) => ({
              duration: item.columns.duration,
              update_time: item.columns.update_time,
              date_time: item.columns.date_time,
              create_time: item.columns.create_time,
              id: item.columns.id,
              status: item.columns.status,
              title: item.columns.title,
              video_url: item.columns.video_url,
              chapter_cover: item.columns.chapter_cover,
              training_id: item.columns.training_id
            }
        ))
      })
    }
  })
}

function onAvatarError(e: any) {
  e.target.src = ren;
  // course.value.teacher.avatar = 'https://img1.imgtp.com/2023/07/21/0QwQwQwQwQ.jpg'
}

function onCoverImageError(e: any) {
  // 可以使用网络默认图片或本地图片
  e.target.src = renBook;
}

// 生命周期
onMounted(() => {
  getCourseInformation()
  updateTime();
  timeInterval = setInterval(updateTime, 60000);
});

onUnmounted(() => {
  if (timeInterval) {
    clearInterval(timeInterval);
  }
});
</script>
